<template>
  <div class="creates">
    <!-- <el-button type="text" @click="bianji()" size="small">编辑</el-button> -->
    <!-- 编辑弹框 -->
    <el-dialog
      title="编辑数据多选"
      :visible.sync="dialogFormVisible"
      :fullscreen="true"
      :before-close="resetForm"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="content">
          <el-form-item label="题目编号" prop="qid">
            <el-input v-model="ruleForm.qid" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="课程名称" prop="sname">
            <el-select v-model="ruleForm.sid" placeholder="请选择活动区域" :loading="tloading">
              <el-option v-for="(v, i) of selList.kList" :key="i" :label="v.sname" :value="v.sid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目类型" prop="tname">
            <el-select
              :disabled="true"
              v-model="ruleForm.tid"
              placeholder="请选择活动区域"
              :loading="tloading"
            >
              <el-option v-for="(v, i) of selList.tList" :key="i" :label="v.tname" :value="v.tid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="难度" prop="nname">
            <el-select v-model="ruleForm.nid" placeholder="请选择活动区域" :loading="nloading">
              <el-option v-for="(v, i) of selList.nList" :key="i" :label="v.nname" :value="v.nid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题干">
            <div ref="box"></div>
          </el-form-item>
        </div>
        <div class="content">
          <el-form-item label="选项">
            <div v-for="(v, i) of ruleForm.answerList" :key="i" style="margin-bottom: 10px">
              <p style="font-size: 30px">选项{{ i + 1 }}</p>
              <div>
                <div :ref="'editor' + i" style="width: 70%; margin-right: 20px; float: left"></div>
                <div style="float: left">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox :label="i">正确答案</el-checkbox>
                  </el-checkbox-group>
                  <div style="clear: both"></div>
                  <el-button
                    icon="el-icon-minus"
                    style="margin-top: 10px"
                    @click="delbox(i)"
                    circle
                    v-if="i != 0"
                  ></el-button>
                </div>
              </div>
              <div style="clear: both"></div>
            </div>
            <el-button icon="el-icon-plus" @click="crebox()" style="margin-top: 10px">添加选项</el-button>
          </el-form-item>
          <el-form-item label="知识点">
            <div ref="box2"></div>
          </el-form-item>
          <el-form-item label="解析">
            <div ref="box3"></div>
          </el-form-item>
        </div>
        <div style="clear: both"></div>
        <div class="but">
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="butLoading">立即修改</el-button>
            <el-button
              @click="
                resetForm('ruleForm');
                dialogFormVisible = false;
              "
            >取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import E from "wangeditor";
import axios from "../../api/home";
import hljs from "highlight.js";
export default {
  props: ["msg"],
  data() {
    return {
      ruleForm: {},
      checkList: [],
      dialogFormVisible: false,
      typescripts: true,
      //下拉框数据
      selList: {
        kList: [],
        tList: [],
        nList: []
      },
      rules: {
        qid: [{ required: true, message: "内容不能为空", trigger: "change" }],
        sList: [{ required: true, message: "内容不能为空", trigger: "change" }],
        tList: [{ required: true, message: "内容不能为空", trigger: "change" }],
        nList: [{ required: true, message: "内容不能为空", trigger: "change" }]
      },
      //富文本编辑器数据
      editor: "",
      editor1: "",
      editor2: "",
      editor3: "",
      //富文本菜单
      menus: [
        "head",
        "bold",
        "fontSize",
        "italic",
        "strikeThrough",
        "indent",
        "foreColor",
        "backColor",
        "list",
        "underline",
        "image",
        "splitLine",
        "undo",
        "redo"
      ],
      fontSizes: {
        "x-small": { name: "10px", value: "1" },
        small: { name: "13px", value: "2" },
        normal: { name: "16px", value: "3" },
        large: { name: "18px", value: "4" },
        "x-large": { name: "24px", value: "5" },
        "xx-large": { name: "32px", value: "6" },
        "xxx-large": { name: "48px", value: "7" }
      },
      //下拉框
      nloading: true,
      tloading: true,
      //添加按钮
      butLoading: false
    };
  },
  methods: {
    //添加选项框
    crebox(val) {
      this.ruleForm.answerList.push({
        editor: null
      });
      let box = this.ruleForm.answerList[this.ruleForm.answerList.length - 1];
      const boxs = "editor" + String(this.ruleForm.answerList.length - 1);
      setTimeout(() => {
        box.editor = new E(this.$refs[boxs]);
        box.editor.config.height = 70;
        box.editor.config.menus = this.menus;
        box.editor.config.fontSizes = this.fontSizes;
        box.editor.config.menuTooltipPosition = "down";
        box.editor.config.zIndex = 99 - this.ruleForm.answerList.length;
        box.editor.highlight = hljs;
        box.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          let formData = new FormData();
          formData.append("file", resultFiles[0]);
          axios
            .upload(formData)
            .then(res => {
              if (res.data.code == 20000) {
                insertImgFn(res.data.url);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(error => {
              this.$message.error(error.message);
            });
        };
        box.editor.create();
        if (val) {
          box.editor.txt.html(val);
        }
      }, 10);
    },
    //删除选项框
    delbox(i) {
      this.checkList = [0];
      let arr = [];
      for (let q = 0; q < this.ruleForm.answerList.length; q++) {
        arr.push(this.ruleForm.answerList[q].editor.txt.html());
      }
      arr.splice(i, 1);
      this.ruleForm.answerList = [];
      for (let w = 0; w < arr.length; w++) {
        setTimeout(() => {
          this.crebox(arr[w]);
        }, 15);
      }
    },
    //配置富文本
    typescript() {
      this.AList();
      // if (this.typescripts) {
      this.typescripts = false;

      this.editor = new E(this.$refs.box);
      this.editor.config.height = 70;
      this.editor.config.menus = this.menus;
      this.editor.config.fontSizes = this.fontSizes;
      this.editor.config.menuTooltipPosition = "down";
      this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let formData = new FormData();
        formData.append("file", resultFiles[0]);
        axios
          .upload(formData)
          .then(res => {
            if (res.data.code == 20000) {
              insertImgFn(res.data.url);
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(error => {
            this.$message.error(error.message);
          });
      };
      this.editor.create();

      // this.editor1 = new E(this.$refs.box1);
      // this.editor1.config.height = 150;
      // this.editor1.config.menus = this.menus;
      // this.editor1.config.fontSizes = this.fontSizes;
      // this.editor1.config.menuTooltipPosition = "down";
      // this.editor1.config.zIndex = 300;
      // this.editor1.create();

      for (let i = 0; i < this.ruleForm.answerList.length; i++) {
        console.log(this.ruleForm.answerList[i].qid);
        this.ruleForm.answerList[i].editor = new E(this.$refs["editor" + i]);
        this.ruleForm.answerList[i].editor.config.height = 70;
        this.ruleForm.answerList[i].editor.config.menus = this.menus;
        this.ruleForm.answerList[i].editor.config.fontSizes = this.fontSizes;
        this.ruleForm.answerList[i].editor.config.menuTooltipPosition = "down";
        this.ruleForm.answerList[i].editor.config.customUploadImg = (
          resultFiles,
          insertImgFn
        ) => {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          let formData = new FormData();
          formData.append("file", resultFiles[0]);
          axios
            .upload(formData)
            .then(res => {
              if (res.data.code == 20000) {
                insertImgFn(res.data.url);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(error => {
              this.$message.error(error.message);
            });
        };
        this.ruleForm.answerList[i].editor.create();
        this.ruleForm.answerList[i].editor.txt.html(
          this.ruleForm.answerList[i].content
        );
        if (this.ruleForm.answerList[i].isRight == 1) {
          this.checkList.push(i);
        }
      }

      this.editor2 = new E(this.$refs.box2);
      this.editor2.config.height = 70;
      this.editor2.config.menus = this.menus;
      this.editor2.config.fontSizes = this.fontSizes;
      this.editor2.config.menuTooltipPosition = "down";
      this.editor2.config.customUploadImg = (resultFiles, insertImgFn) => {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let formData = new FormData();
        formData.append("file", resultFiles[0]);
        axios
          .upload(formData)
          .then(res => {
            if (res.data.code == 20000) {
              insertImgFn(res.data.url);
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(error => {
            this.$message.error(error.message);
          });
      };
      this.editor2.config.zIndex = 200;
      this.editor2.create();

      this.editor3 = new E(this.$refs.box3);
      this.editor3.config.height = 70;
      this.editor3.config.menus = this.menus;
      this.editor3.config.fontSizes = this.fontSizes;
      this.editor3.config.menuTooltipPosition = "down";
      this.editor3.config.customUploadImg = (resultFiles, insertImgFn) => {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let formData = new FormData();
        formData.append("file", resultFiles[0]);
        axios
          .upload(formData)
          .then(res => {
            if (res.data.code == 20000) {
              insertImgFn(res.data.url);
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(error => {
            this.$message.error(error.message);
          });
      };
      this.editor3.config.zIndex = 100;
      this.editor3.create();

      this.editor.txt.html(this.ruleForm.title);
      this.editor2.txt.html(this.ruleForm.remark);
      this.editor3.txt.html(this.ruleForm.analysis);

      // }
    },
    bianji() {
      this.ruleForm = {};
      //   this.resetForm();
      axios
        .getIDti(this.$route.query.qid)
        .then(res => {
          if (res.data.code == 20000) {
            this.ruleForm = res.data.xiangqingDTO;
            this.dialogFormVisible = true;
            setTimeout(() => {
              this.typescript();
            }, 10);
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    //上传数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let arr = [];
          for (let i in this.ruleForm.answerList) {
            let u = true;
            for (let p in this.checkList) {
              if (this.checkList[p] == i) {
                arr.push({
                  content: this.ruleForm.answerList[i].editor.txt.html(),
                  isRight: 1
                });
                u = false;
                break;
              }
            }
            if (u) {
              u = false;
              arr.push({
                content: this.ruleForm.answerList[i].editor.txt.html(),
                isRight: 0
              });
            }
          }
          const data = {
            answerList: arr,
            qid: this.ruleForm.qid,
            sid: this.ruleForm.sid,
            tid: this.ruleForm.tid,
            nid: this.ruleForm.nid,
            title: this.editor.txt.html(),
            remark: this.editor2.txt.html(),
            analysis: this.editor3.txt.html()
          };
          // console.log(this.checkList);
          // console.log(data);
          // return;
          if (data.title == "") {
            this.$message({
              message: "题干不能为空",
              type: "warning"
            });
            return;
          }
          console.log(this.checkList.length);
          
          if (this.checkList.length < 2) {
            this.$message({
              message: "多选至少两个正确答案",
              type: "warning"
            });
            return;
          }
          axios
            .update(data)

            .then(res => {
              if (res.data.code == 20000) {
                this.dialogFormVisible = false;
                this.selList = {};
                this.butLoading = false;
                this.resetForm();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(error => {
              this.$message.error(error.message);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //清除数据
    resetForm(formName) {
      this.$router.push("/home?name=题库管理");
      console.log(formName);
      if (this.editor) {
        this.editor.destroy();
        this.editor = null;
      }
      if (this.editor2) {
        this.editor2.destroy();
        this.editor2 = null;
      }
      if (this.editor3) {
        this.editor3.destroy();
        this.editor3 = null;
      }
      if (this.ruleForm.answerList) {
        for (let i = 0; i < this.ruleForm.answerList.length; i++) {
          this.ruleForm.answerList[i].editor.destroy();
          this.ruleForm.answerList[i].editor = null;
        }
      }
      // this.editor.txt.clear();
      // this.editor1.txt.clear();
      // this.editor2.txt.clear();
      // this.editor3.txt.clear();
      // this.$refs[formName].resetFields();
      // this.ruleForm = {
      //   answer: "",
      //   jiexi: "",
      //   nname: "",
      //   qid: "",
      //   sname: "",
      //   title: "",
      //   tname: "",
      //   xuanxiang: "",
      //   zhishidian: "",
      // };
    },
    //添加下拉菜单
    AList() {
      axios
        .tseleLise()
        .then((res) => {
          this.selList.tList = res.data.list;
          this.tloading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
      axios
        .nseleLise()
        .then((res) => {
          this.selList.nList = res.data.list;
          this.nloading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
      axios
        .ke()
        .then((res) => {
          this.selList.kList = res.data.list.list;
          this.nloading = false;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
  },
  mounted() {
    this.bianji();
  }
};
</script>
<style scoped>
.crebut {
  float: left;
  margin-right: 20px;
  margin-bottom: 30px;
  margin-top: 20px;
}
.content {
  /* width: 50%;
  float: left; */
}
.but {
  /* position: relative;
  top: -63px; */
}
</style>
